package com.dz.lm.common.utils;

import java.net.URLEncoder;
import java.util.HashMap;
import java.util.Map;
import java.util.Random;
import java.util.TreeMap;
import javax.crypto.Mac;
import javax.crypto.spec.SecretKeySpec;
import javax.xml.bind.DatatypeConverter;

public class APIV3SignDemo {
    public static String sign(String s, String key, String method) throws Exception {
        Mac mac = Mac.getInstance(method);
        SecretKeySpec secretKeySpec = new SecretKeySpec(key.getBytes("UTF-8"), mac.getAlgorithm());
        mac.init(secretKeySpec);
        byte[] hash = mac.doFinal(s.getBytes("UTF-8"));
        return DatatypeConverter.printBase64Binary(hash);
    }

    public static String getStringToSign(String method, String endpoint, TreeMap<String, Object> params) {
        StringBuilder s2s = new StringBuilder();
        s2s.append(method).append(endpoint).append("/?");
        for (String k : params.keySet()) {
            s2s.append(k).append("=").append(params.get(k).toString()).append("&");
        }
        return s2s.toString().substring(0, s2s.length() - 1);
    }

    /**
     * 删除签名
     * @param fileId
     * @return
     * @throws Exception
     */
    public static Map getSinature(String fileId) throws Exception {
        Map ret = new HashMap();
        TreeMap<String, Object> params = new TreeMap<String, Object>();
        params.put("Nonce", new Random().nextInt(java.lang.Integer.MAX_VALUE));
        params.put("Timestamp", System.currentTimeMillis() / 1000+"");
        params.put("Region", "");
        params.put("SecretId", "AKIDB9sNdeI0LrAE3ePC8rXzDBvQghUEn14s");
        params.put("Language", "zh-CN");
        params.put("Action", "DeleteMedia");
        params.put("Version", "2018-07-17");
        params.put("FileId", fileId);
        params.put("Token","");
        String str2sign = getStringToSign("POST", "vod.tencentcloudapi.com", params);
        String signature = sign(str2sign, "kGWYVEhutd9PSRDl4A0cy6B1bw2tVryv", "HmacSHA1");
        ret.put("signature",URLEncoder.encode(signature));
        ret.put("Nonce",params.get("Nonce"));
        ret.put("Timestamp",params.get("Timestamp"));
        System.out.println(str2sign);
    return  ret;

    }



}